package com.fbs.job.admin.controller;

import com.fbs.job.admin.core.annotation.PermissionLimit;
import com.fbs.job.admin.core.entity.FbsJobActuator;
import com.fbs.job.admin.core.entity.FbsJobUser;
import com.fbs.job.admin.mapper.FbsJobActuatorMapper;
import com.fbs.job.admin.mapper.JobUserMapper;
import com.fbs.job.admin.service.JobUserService;
import com.fbs.job.core.model.ResultT;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wwd 2024-01-26 15:38
 */
@Controller
@RequestMapping("/user")
public class JobUserController {

    @Resource
    private FbsJobActuatorMapper  fbsJobActuatorMapper;

    @Resource
    private JobUserMapper jobUserMapper;
    @RequestMapping
    @PermissionLimit(adminuser = true)
    public String index(Model model) {
        // 执行器列表
        List<FbsJobActuator> actuatorList = fbsJobActuatorMapper.findAll();
        model.addAttribute("actuatorList", actuatorList);

        return "user/user";
    }




    @RequestMapping("/pageList")
    @ResponseBody
    @PermissionLimit(adminuser = true)
    public Map<String, Object> pageList(@RequestParam(required = false, defaultValue = "0") int page,
                                        @RequestParam(required = false, defaultValue = "10") int rows,
                                        String username, int role) {

        // page list
        List<FbsJobUser> list = jobUserMapper.pageList(page-1, rows, username, role);
        int list_count = jobUserMapper.pageListCount(page-1, rows, username, role);

        // filter
        if (list!=null && list.size()>0) {
            for (FbsJobUser item: list) {
                item.setPassword(null);
            }
        }
        // package result
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("recordsTotal", list_count);		// 总记录数
        maps.put("recordsFiltered", list_count);	// 过滤后的总记录数
        maps.put("data", list);  					// 分页列表
        maps.put("code",0);
        return maps;
    }



    @RequestMapping("/add")
    @ResponseBody
    @PermissionLimit(adminuser = true)
    public ResultT<String> add(@RequestBody FbsJobUser fbsJobUser) {

        // valid username
        if (!StringUtils.hasText(fbsJobUser.getUsername())) {
            return new ResultT<String>(ResultT.FAIL_CODE, "请输入账号" );
        }
        fbsJobUser.setUsername(fbsJobUser.getUsername().trim());
        if (!(fbsJobUser.getUsername().length()>=4 && fbsJobUser.getUsername().length()<=20)) {
            return new ResultT<String>(ResultT.FAIL_CODE, "长度限制[4-20]" );
        }
        // valid password
        if (!StringUtils.hasText(fbsJobUser.getPassword())) {
            return new ResultT<String>(ResultT.FAIL_CODE, "请输入密码" );
        }
        fbsJobUser.setPassword(fbsJobUser.getPassword().trim());
        if (!(fbsJobUser.getPassword().length()>=4 && fbsJobUser.getPassword().length()<=20)) {
            return new ResultT<String>(ResultT.FAIL_CODE, "长度限制[4-20]");
        }
        // md5 password
        fbsJobUser.setPassword(DigestUtils.md5DigestAsHex(fbsJobUser.getPassword().getBytes()));

        // check repeat
        FbsJobUser existUser = jobUserMapper.getByUserName(fbsJobUser.getUsername());
        if (existUser != null) {
            return new ResultT<String>(ResultT.FAIL_CODE, "账号重复" );
        }

        // write
        jobUserMapper.save(fbsJobUser);
        return ResultT.success("保存成功");
    }

    @RequestMapping("/update")
    @ResponseBody
    @PermissionLimit(adminuser = true)
    public ResultT<String> update(HttpServletRequest request,@RequestBody FbsJobUser fbsJobUser) {

        // avoid opt login seft
            FbsJobUser loginUser = (FbsJobUser) request.getAttribute(JobUserService.LOGIN_IDENTITY_KEY);
        if (loginUser.getUsername().equals(fbsJobUser.getUsername())) {
            return new ResultT<String>(ResultT.FAIL_CODE,"禁止操作当前登录账号");
        }

        // valid password
        if (StringUtils.hasText(fbsJobUser.getPassword())) {
            fbsJobUser.setPassword(fbsJobUser.getPassword().trim());
            if (!(fbsJobUser.getPassword().length()>=4 && fbsJobUser.getPassword().length()<=20)) {
                return new ResultT<String>(ResultT.FAIL_CODE, "长度限制[4-20]" );
            }
            // md5 password
            fbsJobUser.setPassword(DigestUtils.md5DigestAsHex(fbsJobUser.getPassword().getBytes()));
        } else {
            fbsJobUser.setPassword(null);
        }

        // write
        jobUserMapper.update(fbsJobUser);
        return ResultT.success("更新成功");
    }

    @RequestMapping("/remove")
    @ResponseBody
    @PermissionLimit(adminuser = true)
    public ResultT<String> remove(HttpServletRequest request, int id) {

        // avoid opt login seft
        FbsJobUser loginUser = (FbsJobUser) request.getAttribute(JobUserService.LOGIN_IDENTITY_KEY);
        if (loginUser.getId() == id) {
            return new ResultT<String>(ResultT.FAIL_CODE, "禁止操作当前登录账号");
        }

        jobUserMapper.delete(id);
        return ResultT.success("删除成功");
    }

    @RequestMapping("/updatePwd")
    @ResponseBody
    public ResultT<String> updatePwd(HttpServletRequest request, String password){

        // valid password
        if (password==null || password.trim().length()==0){
            return new ResultT<String>(ResultT.FAIL_CODE, "密码不可为空");
        }
        password = password.trim();
        if (!(password.length()>=4 && password.length()<=20)) {
            return new ResultT<String>(ResultT.FAIL_CODE, "长度限制[4-20]" );
        }

        // md5 password
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());

        // update pwd
        FbsJobUser loginUser = (FbsJobUser) request.getAttribute(JobUserService.LOGIN_IDENTITY_KEY);

        // do write
        FbsJobUser existUser = jobUserMapper.getByUserName(loginUser.getUsername());
        existUser.setPassword(md5Password);
        jobUserMapper.update(existUser);

        return ResultT.success("修改成功");
    }
}
